package com.ltmonitor.web.controller.mobile;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ltmonitor.entity.FunctionModel;
import com.ltmonitor.entity.Role;
import com.ltmonitor.entity.SystemConfig;
import com.ltmonitor.entity.UserInfo;
import com.ltmonitor.service.IFunctionModelService;
import com.ltmonitor.service.ISystemConfigService;
import com.ltmonitor.service.IUserInfoService;
import com.ltmonitor.util.StringUtil;
import com.ltmonitor.web.controller.GenericAction;
import com.ltmonitor.web.util.JsonMessage;
import com.ltmonitor.web.util.OnlineUser;

/**
 * 移动端登录
 * 
 * @author DELL
 * 
 */
@Controller
@RequestMapping("/mobile")
public class MobileLoginAction extends GenericAction {

	private static final long serialVersionUID = -2574252247068423156L;	

	@Autowired
	private ISystemConfigService systemConfigService;
	@Autowired
	private IFunctionModelService functionModelService;
	@Autowired
	private IUserInfoService userInfoService;
	
	@ResponseBody
	@RequestMapping("/login.action")
	public JsonMessage login(String username, String password) {

		if (StringUtil.isNullOrEmpty(username)) {
			return json(false, "用户名不能为空");
		}
		if (password == null) {
			return json(false, "密码不能为空");
		}

		try {
			String hsql = "from UserInfo where loginName = ? and userState <> ? and deleted = ?";

			UserInfo user = (UserInfo) this.userInfoService.find(hsql,
					new Object[] { username, UserInfo.STATE_SUSPEND, false });

			if (user == null) {
				return json(false, "用户名或密码错误");
			}
			String userpassword = null;
			

			userpassword = user.getPassword();

			//String pwd = StringUtil.encodePassword(userpassword, "md5");

			if (!userpassword.equalsIgnoreCase(password)) {
				return json(false, "用户名或密码不正确");
			}

			// user.setUserType(this.userType);
			String hostName = getRequest().getRemoteHost();
			user.setIp(hostName);
			if (user.getRoles().size() < 1) {
				Role role = new Role();
				role.setName("ROLE_ADMIN");
				user.getRoles().add(role);
			}
			//user.setLoginTime(new Date());
			MobileOnlineUser.onlineUserMap.put(user.getEntityId(), user);
			ArrayList<FunctionModel> authorizedFuncs = new ArrayList();
			if (user.isSuperAdmin()) {
				// 如果是超级用户，将加所有权限,可以分配所有管理部门
				authorizedFuncs = new ArrayList(this.functionModelService.loadAll());
			} else {
				Role r = user.getRole();
				if (r != null) {
					authorizedFuncs.addAll(r.getFuncs());
				}
			}
			// 移动端的权限
			List funcResult = new ArrayList();
			Map userInfoMap = new HashMap();
			//Map funcMap = new HashMap();
			for (FunctionModel f : authorizedFuncs) {
				if (f.getFuncType() == FunctionModel.FUNC_TYPE_MOBILE) {
					funcResult.add(f.getFuncName());
					//funcMap.put(f.getFuncName(), f.getFuncName());
				}
			}
			
			userInfoMap.put("funcs", funcResult);
			SystemConfig sc = systemConfigService.getSystemConfig();

			userInfoMap.put("userId", user.getEntityId());
			userInfoMap.put("name", user.getName());
			userInfoMap.put("loginName", user.getLoginName());

			userInfoMap.put("mapCenterLat", user.getMapCenterLat());
			if (user.getMapCenterLat() > 0) {
				sc.setInitLat(user.getMapCenterLat());
			}
			if (user.getMapCenterLng() > 0) {
				sc.setInitLng(user.getMapCenterLng());
			}

			userInfoMap.put("mapCenterLng", user.getMapCenterLng());

			if (user.getMapLevel() > 0) {
				userInfoMap.put("mapZoom", user.getMapLevel());

				sc.setInitZoomLevel(user.getMapLevel());
			} else {
				userInfoMap.put("mapZoom", 15);
			}

			if (user.getRoles().size() < 1) {
				// if (user.getUserType() == 0) {
				Role role = new Role();
				// role.setDescription(getText("administrator"));
				role.setName("ROLE_ADMIN");
				user.getRoles().add(role);
				// }
			}
			Role r = user.getRole();
			userInfoMap.put("roleName", r.getName());

			// JSONArray roleArray = JSONArray.fromObject(user.getRoles(),
			// this.jsonConfig);

			super.putSession(SESSION_KEY_SYSTEM_CONFIG, sc);
			
			OnlineUser onlineUser = new OnlineUser();
			onlineUser.setUserId(user.getEntityId());
			onlineUser.setMapType(user.getMapType());
			onlineUser.setName(user.getName());
			onlineUser.setSuperAdmin(user.isSuperAdmin());
			onlineUser.setCompanyId(user.getCompanyId());		
			

			super.setOnlineUser(onlineUser);
			super.setAuthorizedDep(user);
			
			this.LogOperation("移动端登录");

			return json(true, userInfoMap);
		} catch (Exception e) {
			this.log.error(e.getMessage(), e);
			return json(false, e.getMessage());
		}

	}

	public void fetchCurrUserInfo() {
		OnlineUser user = getOnlineUser();
		if (user != null) {

		} else {
		}
	}

	public String main() {
		if (this.getOnlineUser() == null)
			return "input";
		return "success";
	}

	private List<FunctionModel> findSubSyssFuncByParnetId(Long id,List<FunctionModel> authorizedFuncs) {
		List subSysFuncs = new ArrayList();

		for (FunctionModel sysFunc : authorizedFuncs) {
			if (sysFunc.getParentId() == id) {
				subSysFuncs.add(sysFunc);
			}
		}
		System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
		Collections.sort(subSysFuncs, new SysFuncComparator());
		return subSysFuncs;
	}

	public String creatorUserFuncTree() {
		return "success";
	}

	/**
	 * 将用户分配的权限转换成主菜单的JSON数据，输出到前台
	 * 
	 * @param authorizedFuncs
	 *            用户分配的功能权限
	 * @param funcType
	 *            主菜单
	 * @return
	 */
	private String convertFuncsToMenu(List<FunctionModel> authorizedFuncs,
			Integer funcType) {
		System.setProperty("java.util.Arrays.useLegacyMergeSort", "true");
		Collections.sort(authorizedFuncs, new Comparator<FunctionModel>() {
			public int compare(FunctionModel obj1, FunctionModel obj2) {

				return obj2.getMenuSort() - obj1.getMenuSort();
			}
		});
		String webPath = getRequest().getContextPath();

		/**
		 * 查找数据库的主菜单的顶级菜单项记录，然后将功能权限作为子菜单加入到顶级菜单中，如果顶级菜单下没有权限，将忽略不显示
		 */
		String hsql = "from FunctionModel where parentId = ? and funcType = ? and deleted = ? order by menuSort";
		List<FunctionModel> subSysFuncs = this.functionModelService.query(hsql,
				new Object[] { Integer.valueOf(-1), 1, false });
		JSONArray jsonArray = new JSONArray();
		for (FunctionModel func : subSysFuncs) {
			List<FunctionModel> childSysFuns = findChidFuncByParentId(
					func.getEntityId(), authorizedFuncs);
			JSONObject menuItem = new JSONObject();
			menuItem.put("id", "" + func.getEntityId());
			menuItem.put("text", func.getDescr());
			menuItem.put("icon", func.getIcon());
			JSONObject attributes = new JSONObject();
			attributes.put("url", func.getUrl());
			menuItem.put("attributes", attributes);

			JSONArray childMenuItems = new JSONArray();
			for (FunctionModel childSysFunc : childSysFuns) {
				JSONObject childItem = new JSONObject();
				childItem.put("id", "" + childSysFunc.getEntityId());
				childItem.put("text", childSysFunc.getDescr());

				childItem.put("icon", childSysFunc.getIcon());
				String url = "";
				if (!StringUtil.isNullOrEmpty(childSysFunc.getUrl())) {
					url = webPath + "/" + func.getUrl() + "/"
							+ childSysFunc.getUrl();
				}

				attributes = new JSONObject();
				attributes.put("url", url);
				childItem.put("attributes", attributes);
				childMenuItems.add(childItem);
			}
			if (childMenuItems.size() > 0) {
				menuItem.put("menu", childMenuItems);
				jsonArray.add(menuItem); // 如果父菜单下没有子菜单，就不显示在前台
			} else if (isAuthorized(func, authorizedFuncs)) {
				jsonArray.add(menuItem);
			}

		}

		return jsonArray.toString();
	}

	private boolean isAuthorized(FunctionModel f,List<FunctionModel> authorizedFuncs) {
		for (FunctionModel fn : authorizedFuncs) {
			if (f.getEntityId() == fn.getEntityId() && fn.getDeleted() == false) {
				return true;
			}
		}
		return false;
	}

	private List<FunctionModel> findChidFuncByParentId(Long parentId,
			List<FunctionModel> authorizedFuncs) {
		List subSysFuncs = new ArrayList();
		for (FunctionModel sysFunc : authorizedFuncs) {
			if (sysFunc.getParentId() == parentId
					&& sysFunc.getDeleted() == false) {
				subSysFuncs.add(sysFunc);
			}
		}

		Collections.sort(authorizedFuncs, new SysFuncComparator());
		return subSysFuncs;
	}

	/**
	 * 退出登录
	 * 
	 * @return
	 */

	@ResponseBody
	@RequestMapping("/logout.action")
	public JsonMessage logout() {
		OnlineUser user = getOnlineUser();
		if (user != null) {

			this.LogOperation("移动端退出登录");
		}
		try {
			this.setOnlineUser(null);
			this.clearSession();
			HttpSession session = getRequest().getSession();
			session.invalidate();// 移出所有
		} catch (Exception e) {
			log.error(e.getMessage(), e);
		}
		return json(true,"");
	}

	public String getMapToolMenu(List<FunctionModel> authorizedFuncs) {
		JSONArray jsonArray = new JSONArray();
		for (FunctionModel root : authorizedFuncs) {
			// FunctionModel root = (FunctionModel) iterator.next();
			if (root.getParentId() != 900200 || root.getDeleted())
				continue;

			JSONObject rootJsonObject = new JSONObject();
			rootJsonObject.put("id", "" + root.getEntityId());

			rootJsonObject.put("text", root.getDescr());
			rootJsonObject.put("icon", root.getIcon());
			rootJsonObject.put("code", root.getFuncName());
			/**
			 * if (this.selectUserFuncsMap.containsKey(root.getId()))
			 * rootJsonObject.put("checked", Boolean.valueOf(true)); else {
			 * rootJsonObject.put("checked", Boolean.valueOf(false)); }
			 */
			JSONObject attributes = new JSONObject();
			attributes.put("funcName", root.getFuncName());
			// attributes.put("style", root.getStyle());
			rootJsonObject.put("attributes", attributes);
			jsonArray.add(rootJsonObject);
		}
		return jsonArray.toString();
	}

	


	class SysFuncComparator implements Comparator<FunctionModel> {
		SysFuncComparator() {
		}

		public int compare(FunctionModel paramT1, FunctionModel paramT2) {
			int sort1 = paramT1.getMenuSort();

			int sort2 = paramT2.getMenuSort();

			return sort1 - sort2;
		}
	}

}
